package com.my.screenadapter.mLruCache;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.bumptech.glide.Glide;
import com.my.screenadapter.Base.BaseActivity;
import com.my.screenadapter.R;
import com.my.screenadapter.View.FullScreenVideoView;
import com.my.screenadapter.net.okhttpDwonload.DonwloadResponseListener;
import com.my.screenadapter.net.okhttpDwonload.OKHttpUtils;
import com.zhy.base.cache.disk.DiskLruCache;
import com.zhy.base.cache.disk.DiskLruCacheHelper;

import org.apache.log4j.Logger;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import butterknife.BindView;
import butterknife.ButterKnife;

import static org.litepal.LitePalApplication.getContext;

public class MLruCacheActivity extends BaseActivity {
    Logger logger = Logger.getLogger(MLruCacheActivity.class);
    @BindView(R.id.iv)
    ImageView iv;
    @BindView(R.id.btn_download)
    Button btnDownload;
    @BindView(R.id.btn_showiv)
    Button btnShowiv;
    @BindView(R.id.btn_put_json)
    Button btnPutJson;
    @BindView(R.id.btn_show_json)
    Button btnShowJson;
    @BindView(R.id.tvJson)
    TextView tvJson;
    @BindView(R.id.iv_right)
    ImageView ivRight;
    @BindView(R.id.btn_put_json2)
    Button btnPutJson2;
    @BindView(R.id.btn_show_video)
    Button btnShowVideo;
    @BindView(R.id.videoview_left)
    FullScreenVideoView videoviewLeft;
    @BindView(R.id.videoview_right)
    FullScreenVideoView videoviewRight;
    private String mdownLoadDir;
    private String mfilesDir;
    private DiskLruCacheHelper diskLruCacheHelper;

    @Override
    protected void init() {
        ///data/data/com.my.screenadapter/files
        mfilesDir = this.getFilesDir().getAbsolutePath() + File.separator + "MLruCache";
        mdownLoadDir = this.getFilesDir().getAbsolutePath() + File.separator + "DownLoad";
        File file = new File(mfilesDir);
        if (!file.exists()) {
            file.mkdirs();
        }
        File filemdownLoadDir = new File(mdownLoadDir);
        if (!filemdownLoadDir.exists()) {
            filemdownLoadDir.mkdirs();
        }
        logger.info("MLruCache  " + mfilesDir);
        logger.info("DownLoad  " + mdownLoadDir);
        int version = 1;
//        the maximum number of bytes this cache should use to store
        int max = 1024 * 1024 * 1024;//1G  1MB = 1024 *1024 byte  这里1024MB
        try {
            DiskLruCache mDiskLruCache = DiskLruCache.open(file, version, 1, max);


            //取
            DiskLruCache.Snapshot snapShot = mDiskLruCache.get("key");
            if (snapShot != null) {
                InputStream is = snapShot.getInputStream(0);
            }
            diskLruCacheHelper = new DiskLruCacheHelper(this, 1, file, max);

//            diskLruCacheHelper.editor("key");
//            diskLruCacheHelper.put("key", new File("abc"));
//            diskLruCacheHelper.get("key");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    protected int initLayoutId() {
        return R.layout.activity_mlru_cache;
    }


    private int imageNum = 0;
    private int strNum = 0;
    private String strAddress;
    private String imageAddress;

    public void downLoadIv(View view) {
        if (imageNum > (Images.imageThumbUrls.length - 1)) {
            imageNum = 0;
        }

        OKHttpUtils.instance().donwloadFile(mdownLoadDir, Images.imageThumbUrls[imageNum], Images.imageThumbUrls[imageNum], new DonwloadResponseListener() {
            @Override
            public void OnSuccess(long bytesRead, long contentLength, boolean done) {

            }

            @Override
            public void onfailure() {

            }

            @Override
            public void onSuccess(File file) {
                diskLruCacheHelper.put(Images.imageThumbUrls[imageNum], file);
                imageAddress = Images.imageThumbUrls[imageNum];

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        iv.setImageDrawable(MLruCacheActivity.this.getResources().getDrawable(R.drawable.ic_launcher));
                    }
                });
            }
        });
    }

    public void showIv(View view) {
        InputStream inputStream = diskLruCacheHelper.get(imageAddress);

        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
        logger.info("showIv imageAddress==" + imageAddress);
        logger.info("showIv inputStream==" + (inputStream == null));
        logger.info("showIv asBitmap==" + ((bitmap == null) ? "null" : bitmap.getHeight()));
        iv.setImageBitmap(bitmap);


        String filePath = diskLruCacheHelper.getFilePath(imageAddress);

        imageNum++;
        Glide.with(this).load(filePath)
                .into(ivRight);


//        diskLruCacheHelper.getAsBitmap()
    }


    public void putJson(View view) {
        if (strNum > (Images.imageThumbUrls.length - 1)) {
            strNum = 0;
        }
        diskLruCacheHelper.put(Images.imageThumbUrls[strNum], Images.imageThumbUrls[strNum] + "   1111   " + (strNum * 10));
        logger.info("Str put == " + Images.imageThumbUrls[strNum] + "   1111   " + (strNum * 10));

    }


    public void showJson(View view) {
        String asString = diskLruCacheHelper.getAsString(Images.imageThumbUrls[strNum]);
        tvJson.setText(asString);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    public void putJson2(View view) {
        diskLruCacheHelper.put(Images.imageThumbUrls[strNum], Images.imageThumbUrls[strNum] + " jjjj22222  " + strNum);
        logger.info("Str put == " + Images.imageThumbUrls[strNum] + " jjjj22222  " + strNum);
    }

    String videoPath = "http:\\/\\/172.16.20.198:8080\\/material\\/video\\/2018\\/06\\/26\\/测试短_1529982343976.mp4";

    public void showVideo(View view) {
        OKHttpUtils.instance().donwloadFile(mdownLoadDir, videoPath, "测试短_1529982343976.mp4", new DonwloadResponseListener() {

            @Override
            public void OnSuccess(long bytesRead, long contentLength, boolean done) {

            }

            @Override
            public void onfailure() {

            }

            @Override
            public void onSuccess(final File file) {
                diskLruCacheHelper.put(videoPath, file);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        String filePath = diskLruCacheHelper.getFilePath(videoPath);
                        logger.info("diskLruCacheHelper  video=== "+filePath);
                        startVideo(filePath, videoviewLeft);
                        startVideo(file.getAbsolutePath(), videoviewRight);
                    }
                });
            }
        });

    }

    private void startVideo(String filePath, final VideoView videoviewLeft) {
        videoviewLeft.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.start();
                mp.setLooping(true);
            }
        });
        MediaController mediaController = new MediaController(getContext());
        mediaController.setAnchorView(videoviewLeft);
        mediaController.setKeepScreenOn(true);
        mediaController.setVisibility(View.GONE);
        videoviewLeft.setMediaController(mediaController);
        videoviewLeft.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {

            }
        });
        videoviewLeft.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {

                mp.stop();
                videoviewLeft.stopPlayback();
                videoviewLeft.setVisibility(View.GONE);

                Toast.makeText(getContext(), "播放失败",
                        Toast.LENGTH_SHORT).show();
                return true;
            }
        });
        videoviewLeft.setVideoPath(filePath);
        videoviewLeft.start();
    }
}
